package com.zrkizzy.module.content.service.config;

import com.zrkizzy.common.core.utils.bean.BeanCopyUtil;
import com.zrkizzy.common.models.domain.blog.article.AboutMe;
import com.zrkizzy.common.models.dto.blog.article.AboutMeDTO;
import com.zrkizzy.common.mongo.service.IMongoService;
import com.zrkizzy.content.facade.service.config.IAboutMeService;
import com.zrkizzy.module.content.constant.DefaultValueConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 关于我业务逻辑接口实现类
 *
 * @author zhangrongkang
 * @since 2023/9/8
 */
@Slf4j
@Service
public class AboutMeServiceImpl implements IAboutMeService {

    @Autowired
    private IMongoService<AboutMe> mongoDbService;

    /**
     * 获取关于我内容
     *
     * @return 关于我对象
     */
    @Override
    public AboutMe getAboutMe() {
        // 根据类型获取所有关于我的集合
        List<AboutMe> aboutMes = mongoDbService.findAll(AboutMe.class);
        // 判断当前是否有数据
        if (CollectionUtils.isEmpty(aboutMes)) {
            AboutMe aboutMe = new AboutMe();
            // 设置初始标题和时间
            aboutMe.setTitle(DefaultValueConst.DEFAULT_ABOUT_ME_TITLE).setUpdateTime(LocalDateTime.now());
            // 在MongoDB中创建数据
            mongoDbService.insert(aboutMe);
            // 返回当前数据
            return aboutMe;
        }
        // 集合中只有一个数据
        return aboutMes.getFirst();
    }

    /**
     * 更新关于我数据
     *
     * @param aboutMeDTO 关于我数据传输对象
     * @return 是否更新成功
     */
    @Override
    public Boolean update(AboutMeDTO aboutMeDTO) {
        // 更新时间
        aboutMeDTO.setUpdateTime(LocalDateTime.now());
        AboutMe aboutMe = mongoDbService.save(BeanCopyUtil.copy(aboutMeDTO, AboutMe.class));
        return null != aboutMe;
    }
}
